<template>
  <el-container style="width: 100%; height: 100%">
    <!-- 头部标题 -->
    <el-header class="header"> 物理运动2</el-header>
    <!-- 主要内容区域，包含 Three.js 画布 -->
    <el-main class="canvas-container">
      <canvas ref="canvas" class="canvas"></canvas>
    </el-main>
  </el-container>
</template>

<script lang="ts">
export default {
  name: 'PhysicalMotion2', // 使用多词名称
}
</script>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { Sky } from 'three/examples/jsm/objects/Sky'
import { ShaderMaterial, MathUtils } from 'three'
import * as Cannon from 'cannon'

// Three.js 相关变量声明
// 场景
let scene: THREE.Scene
// 透视相机
let camera: THREE.PerspectiveCamera
// WebGL渲染器
let renderer: THREE.WebGLRenderer
// 天空
let sky: THREE.Mesh
// 动画帧ID
let animationFrameId: number

let controls: InstanceType<typeof OrbitControls>
let world: InstanceType<typeof Cannon.World>
let texture1: THREE.Texture
const spheres: { sphere: THREE.Mesh; sphereBody: Cannon.Body }[] = []

// 画布引用
const canvas = ref<HTMLCanvasElement>()
// 组件挂载时初始化场景并开始动画
onMounted(() => {
  initScene()
  animate()
  // 添加窗口大小改变事件监听
  window.addEventListener('resize', onWindowResize)
})

// 初始化场景
function initScene() {
  if (!canvas.value) return
  makeRenderer(canvas.value.clientWidth, canvas.value.clientHeight)
  makeScene()
  texture1 = new THREE.TextureLoader().load(new URL('@/assets/img/test.png', import.meta.url).href)

  world = new Cannon.World()
  world.gravity.set(0, -9.82, 0)
  //创建物理材料
  const groundMaterial = new Cannon.Material('groundMaterial')
  const sphereMaterial = new Cannon.Material('sphereMaterial')
  const contactMaterial = new Cannon.ContactMaterial(groundMaterial, sphereMaterial, {
    friction: 0.8,
    restitution: 0.5,
  })
  world.addContactMaterial(contactMaterial)
  makePhysicalGround(groundMaterial)
  canvas.value.addEventListener('mouseup', (event) => {
    const raycaster = new THREE.Raycaster()
    const rect = canvas.value!.getBoundingClientRect() // 获取画布的实际位置和尺寸
    const mouse = new THREE.Vector2()
    mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
    mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1
    raycaster.setFromCamera(mouse, camera)
    createSphere(
      camera.position,
      new Cannon.Vec3(
        raycaster.ray.direction.x,
        raycaster.ray.direction.y,
        raycaster.ray.direction.z,
      ),
      sphereMaterial,
    )
  })
  makeCamera(canvas.value.clientWidth, canvas.value.clientHeight)
  orbitControls()
  addSky()
  addGround()
}

function makePhysicalGround(groundMaterial: Cannon.Material) {
  const groundBody = new Cannon.Body({
    mass: 0,
    shape: new Cannon.Plane(),
    material: groundMaterial,
  })
  groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0)
  world.addBody(groundBody)
}

function createSphere(
  position: THREE.Vector3,
  direction: Cannon.Vec3,
  sphereMaterial: Cannon.Material,
) {
  // 创建可视球体
  const sphere = new THREE.Mesh(
    new THREE.SphereGeometry(2, 32, 32),
    new THREE.MeshBasicMaterial({ map: texture1 }),
  )
  sphere.position.set(0, 10, 0)
  scene.add(sphere)
  // 创建物理球体
  const sphereBody = new Cannon.Body({
    mass: 1,
    shape: new Cannon.Sphere(2),
    position: new Cannon.Vec3(position.x, position.y, position.z),
    material: sphereMaterial,
  })
  sphereBody.linearDamping = 0.2
  sphereBody.angularDamping = 0.4
  sphereBody.applyLocalForce(direction.scale(600), new Cannon.Vec3(0, 0, 0))
  world.addBody(sphereBody)
  spheres.push({ sphere, sphereBody })
}

function updatePhysic() {
  world.step(1 / 60)
  spheres.forEach(({sphere, sphereBody}) => {
    sphere.position.copy(sphereBody.position)
    sphere.quaternion.copy(sphereBody.quaternion)
  })
}

function makeScene() {
  // 创建场景
  scene = new THREE.Scene()
  //添加光源
  const light = new THREE.DirectionalLight(0xffffff, 1)
  scene.add(light)
}

function makeRenderer(width: number, height: number) {
  // 创建WebGL渲染器
  renderer = new THREE.WebGLRenderer({ canvas: canvas.value, antialias: true })
  renderer.setSize(width, height)
  // 设置设备像素比，确保在高分辨率屏幕上清晰显示
  renderer.setPixelRatio(window.devicePixelRatio)
}

function makeCamera(width: number, height: number) {
  // 创建透视相机
  camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)
  // 设置相机位置
  camera.position.set(0, 10, 20)
  camera.lookAt(0, 0, 0)
}

function orbitControls() {
  controls = new OrbitControls(camera, canvas.value)

  // 限制摄像机的极角范围（单位是弧度）
  controls.minPolarAngle = 0 // 最小角度，0 表示水平视角
  controls.maxPolarAngle = MathUtils.degToRad(85) // 最大角度，例如 85 度

  // 可选：限制摄像机的缩放范围
  controls.minDistance = 5 // 最小距离
  controls.maxDistance = 100 // 最大距离
}

function addSky() {
  sky = new Sky()
  sky.scale.setScalar(450000) // 设置天空的缩放比例
  scene.add(sky)

  const sun = new THREE.Vector3()

  // 配置天空参数
  const effectController = {
    turbidity: 2,
    rayleigh: 4,
    mieCoefficient: 0.001,
    mieDirectionalG: 0,
    elevation: 2,
    azimuth: 160,
    exposure: renderer.toneMappingExposure,
  }

  const uniforms = (sky.material as ShaderMaterial).uniforms
  uniforms['turbidity'].value = effectController.turbidity
  uniforms['rayleigh'].value = effectController.rayleigh
  uniforms['mieCoefficient'].value = effectController.mieCoefficient
  uniforms['mieDirectionalG'].value = effectController.mieDirectionalG

  const phi = THREE.MathUtils.degToRad(90 - effectController.elevation)
  const theta = THREE.MathUtils.degToRad(effectController.azimuth)

  sun.setFromSphericalCoords(1, phi, theta)

  uniforms['sunPosition'].value.copy(sun)
}

// 添加大地
function addGround() {
  const texture = new THREE.TextureLoader().load(
    new URL('@/assets/img/caoyuan.png', import.meta.url).href,
  )
  const groundGeometry = new THREE.PlaneGeometry(100, 100)
  const groundMaterial = new THREE.MeshStandardMaterial({
    color: 0x7ec850, // 绿色草地颜色
    side: THREE.DoubleSide,
    map: texture,
  })

  const ground = new THREE.Mesh(groundGeometry, groundMaterial)
  ground.rotation.x = Math.PI / 2 // 旋转平面使其水平
  scene.add(ground)
}

// 动画循环函数
function animate() {
  animationFrameId = requestAnimationFrame(animate)
  controls.update()
  updatePhysic()
  // 渲染场景
  renderer.render(scene, camera)
}

// 清理函数
function cleanup() {
  // 取消动画帧`
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }

  // 清理渲染器
  if (renderer) {
    // 移除所有事件监听器
    renderer.domElement.removeEventListener('resize', onWindowResize)
    // 释放渲染器资源
    renderer.dispose()
    // 清空渲染器
    renderer.forceContextLoss()
    // 移除画布
    renderer.domElement.remove()
  }

  // 清理场景
  if (scene) {
    // 遍历场景中的所有对象
    scene.traverse((object) => {
      if (object instanceof THREE.Mesh) {
        // 释放几何体资源
        object.geometry.dispose()
        // 释放材质资源
        if (Array.isArray(object.material)) {
          object.material.forEach((material) => material.dispose())
        } else {
          object.material.dispose()
        }
      }
    })
    // 清空场景
    scene.clear()
  }

  // 清理相机
  if (camera) {
    camera.clear()
  }
}

// 窗口大小改变时的处理函数
function onWindowResize() {
  if (!canvas.value) return
  const width = canvas.value.clientWidth
  const height = canvas.value.clientHeight
  console.log('onWindowResize', width, height)
  // 更新相机
  camera.aspect = width / height
  camera.updateProjectionMatrix()

  // 更新渲染器
  renderer.setSize(width, height)
  // 确保渲染器的像素比与设备匹配
  renderer.setPixelRatio(window.devicePixelRatio)
}

// 组件卸载时清理资源
onUnmounted(() => {
  cleanup()
  // 移除窗口大小改变事件监听
  window.removeEventListener('resize', onWindowResize)
})
</script>

<style scoped>
/* 头部样式 */
.header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

/* 画布容器样式 */
.canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 画布样式   // 保持画布比例*/
.canvas {
  width: 100%;
  height: 100%;
}
</style>
